export default class TaskManager {
    constructor() {
        this._tasks = [];
        this._running = false;
        this._currentIndex = 0;
        this._next = async () => {
            this._currentIndex++;
            await this._runTask();
        };
    }

    addTask(task) {
        if (typeof task !== 'function') throw 'Task should be a function!';
        this._tasks.push(task);
    }

    run() {
        if (this._running || !this._tasks.length) return;
        // 开始运行
        this._running = true;

    }

    async _runTask() {
        if (this._currentIndex >= this._tasks.length) return this._reset();
        // 记录当前任务下标
        const i = this._currentIndex;
        // 执行当前任务
        const task = this._tasks[this._currentIndex];
        await task(this._next);
        // 若未调用next，则自动调用
        if (i === this._currentIndex) await this._next();
    }

    _reset() {
        this._tasks = [];
        this._currentIndex = 0;
        this._running = false;
    }
};